package com.chensi.admin.shop.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Optional;

public class DateUtil {
    public static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_WECHAT_NOTIFY = "HH:mm:ss yyyy-MM-dd";
    public static final long ONE_DAY = 24 * 60 * 60;
    public static final long ONE_HOUR = 60 * 60;


    public static String getLastMonth(String format) {
        LocalDateTime dateTime = LocalDateTime.now().withDayOfMonth(1)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .minusMonths(1);
        return date(dateTime, format);
    }

    public static String getLastMonth() {
        return getLastMonth(DATE_FORMAT_DEFAULT);
    }

    public static String now() {
        return org.apache.http.client.utils.DateUtils.formatDate(new Date(), DATE_FORMAT_DEFAULT);
    }

    public static String date(LocalDateTime dateTime, String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        dateTime = Optional.ofNullable(dateTime).orElseGet(LocalDateTime::now);
        return dateTime.format(formatter);
    }

    public static String date(LocalDateTime dateTime) {
        return date(dateTime, DATE_FORMAT_DEFAULT);
    }

    public static int intervalNow(LocalDateTime createTime) {
        long epochSecond = createTime.atZone(ZoneId.systemDefault())
                .toInstant().getEpochSecond();
        long now = Instant.now().getEpochSecond();
        long is = now - epochSecond;
        /*long days = is / ONE_DAY;
        long hours = (is - days * ONE_DAY) / ONE_HOUR;
        long minutes = (is - days * ONE_DAY - hours * ONE_HOUR) / 60;
        long seconds = is % 60;
        StringBuilder sb = new StringBuilder();
        if (days > 0) sb.append(days).append("天");
        if (hours > 0) sb.append(hours).append("小时");
        if (minutes > 0) sb.append(minutes).append("分钟");
        if (seconds > 0) sb.append(seconds).append("秒");*/
        return (int) (is / 60);
    }
}
